package com.foreknow.dao.impl;

import com.foreknow.bean.Guestbook;
import com.foreknow.dao.BaseDao;
import com.foreknow.dao.GuestbookDao;
import com.foreknow.mapping.EntityMapping;
import com.foreknow.mapping.MappingFactory;

import java.sql.SQLException;
import java.util.List;

public class GuestbookDaoImpl extends BaseDao implements GuestbookDao {
    @Override
    public int add(Guestbook guestbook) throws SQLException {
        String sql = "insert into guestbook(name,phone,email,title,content,createdtime) values(?,?,?,?,?,?)";
        int a = jdbcTemplate.update(sql,guestbook.getName(),guestbook.getPhone(),guestbook.getEmail(),guestbook.getTitle(),guestbook.getContent(),guestbook.getCreatedtime());
        return a;
    }

    @Override
    public Guestbook query(Integer id) throws SQLException{
        String sql = "select * from guestbook where id = ?";
        EntityMapping entityMapping = mappingFactory.getmapping(MappingFactory.GUESTBOOK_MAPPING);
        List<Object> list = jdbcTemplate.query(sql,entityMapping,id);
        if (list.size()>0){
            Guestbook guestbook = (Guestbook) list.get(0);
            return guestbook;
        }
        return null;
    }

    @Override
    public List<Object> mohuquery(String name) throws SQLException{
        String sql = "select * from guestbook where name like ?";
        String name1 = "%"+name+"%";
        EntityMapping entityMapping = mappingFactory.getmapping(MappingFactory.GUESTBOOK_MAPPING);
        List<Object> list = jdbcTemplate.query(sql,entityMapping,name1);
        return list;
    }

    @Override
    public int delete(Integer id) throws SQLException{
        String sql = "delete from guestbook where id = ?";
        int a = jdbcTemplate.update(sql,id);
        return a;
    }

    @Override
    public int update(Guestbook guestbook) throws SQLException{
        String sql = "update guestbook set name = ? , phone = ? , email = ? , title = ? , content = ? , createdtime= ? where id= ?";
        int a = jdbcTemplate.update(sql,guestbook.getName(),guestbook.getPhone(),guestbook.getEmail(),guestbook.getTitle(),guestbook.getContent(),guestbook.getCreatedtime(),guestbook.getId());
        return a;
    }

    @Override
    public List<Object> allquery() throws SQLException{
        String sql = "select * from guestbook";
        EntityMapping entityMapping = mappingFactory.getmapping(MappingFactory.GUESTBOOK_MAPPING);
        List<Object> list = jdbcTemplate.query(sql,entityMapping);
        return list;
    }
}
